import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {Image, View, Text, Block, Button} from "@tarojs/components";
import {AtCountdown, AtFloatLayout, AtIcon, AtModal, AtModalAction, AtModalContent, AtModalHeader} from "taro-ui";
import {h5Wx} from "../../utils/h5.service";
import './detail.scss'
import {user} from "../../utils/user.service";
import {
  ACTIVITY_GROUP_ACTIVITY_INFO,
  SHARE_POSTER,
  ACTIVITY_GROUP_BUY_DETAIL,
  RESOURCE_URL,
  TARO_ENV,
  ACTIVITY_GET_CODE,
  SHORT_URL, UPDATE_USER_SHARE_DATE
} from "../../constants/api";
import {GetRequest, vcmonitor} from "../../utils/tools";
import {http} from "../../utils/http";
import Float from "../../components/float/float";
import {newHttp} from "../../utils/request";

export default class Index extends Component {
  state: {
    showAllMembers: boolean
    inviteFriends: boolean
    modalShow: boolean
    shareShow: boolean
    sharePoster: boolean
    info: object
    codeInfo: any
    userList: any
    allMembers: any
    joinPeople: any
    detail: any
    imgSrc: string
  } = {
    imgSrc: '',
    showAllMembers: false,
    inviteFriends: false,
    modalShow: false,
    shareShow: false,
    sharePoster: false,
    joinPeople: null,
    codeInfo: null,
    detail: null,
    userList: []
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    this.shareParams = await user.getSellerParams()
    const orderNum = this.params.orderNum
    this.category = this.params.category
    this.itemId = this.params.itemId
    const showLeadModel = this.params.showLeadModel || false
    const data = await http.HGet(ACTIVITY_GROUP_ACTIVITY_INFO, {order_num: orderNum})
    const datas = await http.HGet(ACTIVITY_GROUP_BUY_DETAIL, {group_buy_id: data.data.group_buy_id})
    const codeInfo = await http.HGet(ACTIVITY_GET_CODE, {order_num: orderNum, send_type: 5})
    const joinPeople = datas.data.join_people
    const userList = []
    const len = datas.data.join_people.length
    if (len !== data.all_people_num) {
      const number = data.data.all_people_num >= 5 ? 5 : data.data.all_people_num
      for (let i = 0; i < number; i++) {
        if (i + 1 <= len) {
          userList.push(joinPeople[i])
        } else {
          userList.push({
            head_img: 'https://img.yzcdn.cn/public_files/2018/09/05/e0ff5968e453ee8811e43ac232e537a8.png',
            isPlaceholder: true
          })
        }
      }
    }
    if (data.data.goods_uuid) {
      this.itemId = data.data.goods_uuid
    }
    if (data.data.status === -1 && TARO_ENV === 'weapp') {
      Taro.hideShareMenu()
    }
    this.setState({joinPeople: joinPeople, detail: data.data, userList, codeInfo})
    if (process.env.TARO_ENV === 'h5' && data.data.status !== -1) {
      let category = 'scenic'
      if (this.category === '4'){
        category = 'product'
      } else if (this.category === '0'){
        category = 'limited'
      }
      const o = window.location.origin
      const _title = '【仅剩'+data.data.rest_num+'人】'+data.data.goods_name;
      const shareData = {
        title: _title,
        desc: data.data.goods_lightspot ? data.data.goods_lightspot : data.data.goods_name,
        link: o + `/common/${category}/detail?itemId=${this.itemId}&${this.shareParams}&groupBuyId=${data.data.group_buy_id}`,
        imgUrl: data.data.goods_img
      }
      h5Wx.share(shareData)
    }
    if (codeInfo && codeInfo.data !== 'variable_code_close' && data.data.is_show_variable_code === 1){
      this.setState({modalShow: true})
    }
    if (JSON.parse(showLeadModel)){
      this.setState({ shareShow: true })
    }
  }

  shareParams
  category
  itemId
  params = Taro.getCurrentInstance().router.params

  /* 分享好友 */
  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    const {detail} = this.state
    let category = 'scenic'
    if (this.category === '4'){
      category = 'product'
    } else if (this.category === '0'){
      category = 'limited'
    }
    const path = `/common/${category}/detail?itemId=${this.itemId}&${this.shareParams}&groupBuyId=${detail.group_buy_id}` + `&sKey=${Taro.getStorageSync('sKey' || '')}`
    return {
      path,
      title: detail.goods_name,
      imageUrl: detail.goods_img
    };
  }

  jump() {
    Taro.navigateTo({url: `/common/group/play?category=${this.state.detail.type}`})
  }

  shareHandler() {
    this.setState({shareShow: true})
  }

  async onCopy() {
    try {
      const {detail} = this.state
      let category = 'scenic'
      if (this.category === '4'){
        category = 'product'
      } else if (this.category === '0'){
        category = 'limited'
      }
      let uri = `/common/${category}/detail?itemId=${this.itemId}&${this.shareParams}&groupBuyId=${detail.group_buy_id}`
      if (TARO_ENV === 'h5') {
        uri = window.location.origin + uri
        const jsonObj = await newHttp.post(SHORT_URL, {longUrl:uri})
        uri = jsonObj.data;
      }
      Taro.setClipboardData({
        data: uri,
        success: () => {
          Taro.showToast({title: '复制成功'})
        }
      })
    } catch (e) {
      Taro.showToast({title: '复制失败'})
    }
  }

  async sharePoster() {
    const {detail} = this.state
    this.setState({inviteFriends: false,shareShow: false, modalShow: false})
    let category = 'scenic'
    if (this.category === '4'){
      category = 'product'
    } else if (this.category === '0'){
      category = 'limited'
    }
    let mpkey = ''
    const uInfo = Taro.getStorageSync('user') || ''
    if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
      mpkey = uInfo.mpkey
    }
    const params = {
      group_activity_id: detail.group_buy_id,
      code_flag: TARO_ENV === 'h5' ? 1 : 0,
      wxx_path: `/common/${category}/detail?itemId=${this.itemId}&${this.shareParams}&groupBuyId=${detail.group_buy_id}&mpkey=${mpkey}`
    }
    Taro.showLoading({title: '加载中...'})
    const data = await http.post(SHARE_POSTER, params)
    if (data){
      this.setState({
        sharePoster: true,
        imgSrc: data
      })
    }
    Taro.hideLoading()
  }
  handleCancel() {
    this.setState({modalShow: false})
  }
  componentWillUnmount() {
    this.setState({modalShow: false})
  }
  savePhoto() {
    if (TARO_ENV === 'h5'){
      return
    }
    Taro.showLoading({title: '下载中...'})
    Taro.getImageInfo({
      src: this.state.imgSrc,
    }).then((res) => {
      Taro.saveImageToPhotosAlbum({
        filePath: res.path,
      }).then(() => {
        Taro.hideLoading()
        Taro.showToast({
          title: '保存成功，请进入相册查看',
          icon: 'none'
        })
      })
    }).catch(err => {
      Taro.hideLoading()
      console.log(err)
    })
  }

  imgClick() {
    Taro.previewImage({
      current: this.state.imgSrc,
      urls: [this.state.imgSrc]
    })
  }

  render() {
    const dataColor = Taro.getStorageSync('colorData');
    const {imgSrc, codeInfo, modalShow,joinPeople, detail, userList, showAllMembers, inviteFriends, shareShow, sharePoster} = this.state
    return (
      <View className='detail-wrapper'>
        {detail && <View className='root'>
          <View className='root__bg' />
          <View className='root-title' />
          <View className='goods-wrap'>
            <View className='good-img'><Image className='img' src={detail.goods_img} mode='aspectFill' /></View>
            <View className='pro-info'>
              <View className='pro-name'>{detail.goods_name}</View>
              <View className='price-box'>
                <View className='price' style={`color: ${dataColor.priceColor}`}><Text className='symbol'
                  style={`color: ${dataColor.priceColor}`}
                >￥</Text><Float value={detail.total_fee} />
                </View>
                <View className='market_price'><Text className='price'
                  style={`color: ${dataColor.originalPriceColor}`}
                >价格</Text>
                  <View className='line-through'>
                    <Text className='symbol' style={`color: ${dataColor.originalPriceColor}`}>￥</Text><Text
                      className='price '
                      style={`color: ${dataColor.originalPriceColor}`}
                    >{detail.goods_market_price}</Text>
                  </View>
                </View>
              </View>
            </View>
          </View>
          { !!detail.all_people_num &&
          <View onClick={this.jump.bind(this)} className='rule'>
            <View className='rule-content'><Image mode='aspectFill'
              src='https://resource.ivcheng.com/upload/images/e564d6fc-875f-44a3-99ee-cf8e03b8946c.jpg'
              className='img'
            />拼团规则：邀请{detail.all_people_num}人参团，人数不足自动退款</View>
            <AtIcon value='chevron-right' className='chevron-right-icon' size={16}
              color='#000'
            />
          </View>}
        </View>}
        {detail && <View className='order-detail'>
          <View>
            {detail.status >= 1 && <View className='group-success' style='text-align:center;'><Image mode='widthFix'
              src='https://resource.ivcheng.com/upload/images/20210927/1632712169387_149.png'
              className='img'
            /></View>}
            {detail.status !== 1 && <View className='group-header'>
              <View className='line' />
              <View className='dot' />
              <View className='title'>拼团剩余时间</View>
              <View className='dot' />
              <View className='line' />
            </View>}
            {detail && detail.status !== 1 && detail.date_poor &&
            <AtCountdown isCard isShowDay format={{day: '天', hours: ':', minutes: ':', seconds: ''}} seconds={0}
              day={JSON.parse(detail.date_poor).day} hours={JSON.parse(detail.date_poor).hour}
              minutes={JSON.parse(detail.date_poor).min}
            />}
            <View className='avatar-wrap'>
              {userList.map((item, index) => <View className='avatar-wrap-item'
                style={`z-index: ${userList.length - index}`}
              >
                {index <= 4 && <Block>
                  {userList.length >= 5 && index === 2 && <Text
                    className={`avatar-list-wrap-item-ellipsis ${TARO_ENV + '-avatar-list-wrap-item-ellipsis'}`}
                  >...</Text>}
                  {userList.length >= 5 && index !== 2 &&
                  <Image src={item.head_img} className={`img ${item.isPlaceholder && 'item__img--noborder'}`} />}
                  {userList.length < 5 &&
                  <Image src={item.head_img} className={`img ${item.isPlaceholder && 'item__img--noborder'}`} />}
                </Block>}
                {!!item.is_leader && <View className='item__tag' style={`z-index: ${userList.length}`}>团长</View>}
              </View>)}
            </View>
            <View onClick={() => {
              this.setState({showAllMembers: true})
            }} className='groupon-participants__btn'
            >查看全部团员</View>
            {!!detail.rest_num &&
            <View className='need-num'>还差 <Text className='nums' decode>{detail.rest_num}</Text>人，即可拼团成功！</View>}
            {/*<View className='need-num share-need-num'><Text className='nums share-num' decode>分享到3个群，拼团成功率98%</Text></View>*/}
          </View>
          {detail.status !== -1 && <View className='btn-wrapper'>
            {!!detail.rest_num &&
            <View className='invite-friends' onClick={() => this.setState({inviteFriends: true})}>邀请好友参团</View>}
            <View className={`${!!detail.rest_num ? 'view-order-detail' : 'invite-friends'}`} onClick={() => {
              Taro.navigateTo({url: `/main/order/detail?orderId=${detail.order_num}`})
            }}
            >查看订单</View>
          </View>}
        </View>}
        {showAllMembers &&
        <AtFloatLayout isOpened={showAllMembers} title='查看我的团' className='showAllMembersCla' onClose={() => this.setState({showAllMembers: false})}>
          {joinPeople.map((item, index) => <View className='members-box'>
            <View className='members-item'>
              <View className='member-item-left'>
                <Image src={item.head_img} className='img' />
              </View>
              <View className='member-item-right'>
                <View className='u-name'>
                  {item.nick_name} {!!item.is_leader && <Text className='team-king'>团长</Text>}
                </View>
                <View className='join-time'>{item.add_date}{!!item.is_leader ? '开团' : '参团'}</View>
              </View>
            </View>
            {index !== joinPeople.length - 1 && <View className='line' />}
          </View>)}
        </AtFloatLayout>}
        {showAllMembers && <View className='understood' onClick={() => this.setState({showAllMembers: false})}>
          <View className='understood-btn'>知道了</View>
        </View>}
        {inviteFriends && <View className='inviteFriends-box'>
          <View className='overlay' onClick={() => this.setState({inviteFriends: false})} />
          <View className='invite-box-wrapper'>
            <View className='inviteFriends-box-title'>立即分享好友</View>
            <View className='invite-box'>
              {process.env.TARO_ENV === 'h5' &&
              <View className='invite-box-item' onClick={this.shareHandler.bind(this)}>
                <View className='img-icon'><Image src={RESOURCE_URL + '/resources/images/wx.png'} className='img' /></View>
                <View className='invite-box-item-name'>微信</View>
              </View>}
              {process.env.TARO_ENV !== 'h5' && <Button className='share-box invite-box-item' openType='share'>
                <View className='img-icon'><Image src={RESOURCE_URL + '/resources/images/wx.png'}
                  className='img'
                /></View>
                <View className='invite-box-item-name item-name-h5'>微信</View>
              </Button>}
              <View className='invite-box-item' onClick={this.onCopy.bind(this)}>
                <View className='img-icon'><Image src={RESOURCE_URL + '/resources/images/link.png'} className='img' /></View>
                <View className='invite-box-item-name'>复制链接</View>
              </View>
              <View className='invite-box-item' onClick={this.sharePoster.bind(this)}>
                <View className='img-icon'><Image src={RESOURCE_URL + '/resources/images/img.png'} className='img' /></View>
                <View className='invite-box-item-name'>分享海报</View>
              </View>
            </View>
            <View onClick={() => this.setState({inviteFriends: false})} className='invite-cancel'>取消</View>
          </View>
        </View>}
        {shareShow && <View className='H5shareBox' onClick={() => this.setState({shareShow: false})}>
          <Image className='H5shareImg' src='https://resource.ivcheng.com/upload/images/20210927/1632709048900_196.png'
            mode='widthFix'
          />
        </View>}
        {sharePoster && <View className='share-poster'>
          <View className='share-poster-bg' />
          <View className='share-poster-container'>
            <View className='share-poster-body'>
              <View onClick={() => this.setState({sharePoster: false})} className='share-poster-close'>
                <AtIcon value='close-circle' size='24' color='#fff' />
              </View>
              <View onClick={this.imgClick.bind(this)}>
                <Image className='gzh-close-img'
                  src={imgSrc}
                  mode='widthFix'
                />
              </View>
              <View className='saveToPhoto-box' onClick={this.savePhoto.bind(this)}>
                {TARO_ENV === 'weapp' ? <View className='saveToPhoto'>保存到相册</View> :
                  <View className='saveToPhoto'>请长按图片保存至相册</View>}
              </View>
            </View>
          </View>
        </View>}
        { modalShow && <AtModal className='modal_concatWx-group' isOpened={modalShow} onClose={this.handleCancel.bind(this)}>
          <AtModalHeader>{ detail.big_str && <View>{ detail.big_str }</View> }</AtModalHeader>
          <AtModalContent>
            { detail.small_str && <View className='getCode'>{ detail.small_str }</View> }
            <Image
              mode='aspectFill'
              style='width: 120px;height: 120px;'
              src={codeInfo.data.code}
            />
          </AtModalContent>
          <AtModalAction><Text className='modal_txt'>{detail.under_small_str}</Text></AtModalAction>
        </AtModal> }
        {TARO_ENV === 'h5' && <View className='back-home-icon' style='bottom: calc(env(safe-area-inset-bottom) + 60px)' onClick={()=> window.location.href = window.location.origin + '/pages/index/index'}>
          <AtIcon value='icon icon-shouye-01' size='24px' color='#000' customStyle='line-height: inherit;position:relative;top:-2px' />
        </View>}
      </View>
    )
  }
}
